<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"vchao.top","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="校园通讯录功能，收集校园内的公开联系方式等内容，并进行展示。在日常生活中经常可能需要用到。比如 水电处问题了找水电师傅，招生就业办，学工办的电话等等。  当然，出于隐私考虑，个人手机号不会被收集展示。只展示办公室联系方式等可在网上或校园内查到的号码。  前言校园通讯录模块旨在打造便捷的校园信息服务平台，完善校园信息服务，给校园信息的管理和维护提供更便捷、更安全的服务系统。（本文对该模块进行简易实现">
<meta property="og:type" content="article">
<meta property="og:title" content="手把手带你撸一个校园APP（八）：校园通讯录模块">
<meta property="og:url" content="http://vchao.top/2021/08/25/%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%A6%E4%BD%A0%E6%92%B8%E4%B8%80%E4%B8%AA%E6%A0%A1%E5%9B%ADAPP%EF%BC%88%E5%85%AB%EF%BC%89%EF%BC%9A%E6%A0%A1%E5%9B%AD%E9%80%9A%E8%AE%AF%E5%BD%95%E6%A8%A1%E5%9D%97/index.html">
<meta property="og:site_name" content="乘风破浪">
<meta property="og:description" content="校园通讯录功能，收集校园内的公开联系方式等内容，并进行展示。在日常生活中经常可能需要用到。比如 水电处问题了找水电师傅，招生就业办，学工办的电话等等。  当然，出于隐私考虑，个人手机号不会被收集展示。只展示办公室联系方式等可在网上或校园内查到的号码。  前言校园通讯录模块旨在打造便捷的校园信息服务平台，完善校园信息服务，给校园信息的管理和维护提供更便捷、更安全的服务系统。（本文对该模块进行简易实现">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200219225503419.gif">
<meta property="article:published_time" content="2021-08-25T14:42:51.210Z">
<meta property="article:modified_time" content="2021-08-25T14:37:20.810Z">
<meta property="article:author" content="vchao">
<meta property="article:tag" content="Android">
<meta property="article:tag" content="科师有约">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20200219225503419.gif">

<link rel="canonical" href="http://vchao.top/2021/08/25/%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%A6%E4%BD%A0%E6%92%B8%E4%B8%80%E4%B8%AA%E6%A0%A1%E5%9B%ADAPP%EF%BC%88%E5%85%AB%EF%BC%89%EF%BC%9A%E6%A0%A1%E5%9B%AD%E9%80%9A%E8%AE%AF%E5%BD%95%E6%A8%A1%E5%9D%97/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>手把手带你撸一个校园APP（八）：校园通讯录模块 | 乘风破浪</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">乘风破浪</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://vchao.top/2021/08/25/%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%A6%E4%BD%A0%E6%92%B8%E4%B8%80%E4%B8%AA%E6%A0%A1%E5%9B%ADAPP%EF%BC%88%E5%85%AB%EF%BC%89%EF%BC%9A%E6%A0%A1%E5%9B%AD%E9%80%9A%E8%AE%AF%E5%BD%95%E6%A8%A1%E5%9D%97/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="vchao">
      <meta itemprop="description" content="怀揣好奇，梦想改变世界的菜鸟极客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="乘风破浪">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          手把手带你撸一个校园APP（八）：校园通讯录模块
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-08-25 22:42:51 / 修改时间：22:37:20" itemprop="dateCreated datePublished" datetime="2021-08-25T22:42:51+08:00">2021-08-25</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index"><span itemprop="name">Android</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>校园通讯录功能，收集校园内的公开联系方式等内容，并进行展示。在日常生活中经常可能需要用到。比如 水电处问题了找水电师傅，招生就业办，学工办的电话等等。</p>
<blockquote>
<p>当然，出于隐私考虑，个人手机号不会被收集展示。只展示办公室联系方式等可在网上或校园内查到的号码。</p>
</blockquote>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>校园通讯录模块旨在打造便捷的校园信息服务平台，完善校园信息服务，给校园信息的管理和维护提供更便捷、更安全的服务系统。<br>（本文对该模块进行简易实现，仅讲述通讯录列表样式的展示）</p>
<h4 id="系列文章"><a href="#系列文章" class="headerlink" title="系列文章"></a>系列文章</h4><p>Github地址： <a target="_blank" rel="noopener" href="https://github.com/zhengweichao/Hevttc">科师有约校园APP</a></p>
<ol>
<li><a target="_blank" rel="noopener" href="https://vchao.blog.csdn.net/article/details/80787263">手把手带你撸一个校园APP（一）：项目简介</a></li>
<li><a target="_blank" rel="noopener" href="https://vchao.blog.csdn.net/article/details/81456617">手把手带你撸一个校园APP（二）：应用启动和欢迎页面</a></li>
<li><a target="_blank" rel="noopener" href="https://vchao.blog.csdn.net/article/details/81837608">手把手带你撸一个校园APP（三）：用户模块（登录注册等）</a></li>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/zheng_weichao/article/details/104209803">手把手带你撸一个校园APP（四）：APP框架及功能设计</a></li>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/zheng_weichao/article/details/104227390">手把手带你撸一个校园APP（五）：新闻页面中心模块</a></li>
<li><a target="_blank" rel="noopener" href="https://vchao.blog.csdn.net/article/details/104245390">手把手带你撸一个校园APP（六）：失物招领&amp;二手交易模块</a></li>
<li><a target="_blank" rel="noopener" href="https://vchao.blog.csdn.net/article/details/104273994">手把手带你撸一个校园APP（七）：校园文化模块（社团活动&amp;表白墙&amp;图说校园）</a></li>
<li><strong>手把手带你撸一个校园APP（八）：校园通讯录模块</strong></li>
<li>手把手带你撸一个校园APP（九）：课程表模块（模拟登陆爬取教务处课程信息）</li>
<li>手把手带你撸一个校园APP（十）：APP通用模块（更新，意见反馈等）</li>
</ol>
<h2 id="实现效果"><a href="#实现效果" class="headerlink" title="实现效果"></a>实现效果</h2><p>校园通讯录：<br><img src="https://img-blog.csdnimg.cn/20200219225503419.gif" alt="校园通讯录"></p>
<h2 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h2><ol>
<li>校园通讯录数据部分比较简单，总共 姓名称呼，部门，联系方式 3个主要字段即可；</li>
<li>通讯录列表的数据需要排序分组后再显示；<blockquote>
<p>  <strong>排序</strong>：</p>
<pre><code> 按照姓名称呼的首字母拼音排序 
</code></pre>
<p>  ==&gt; 需要获取首字的拼音 </p>
<pre><code>  ==&gt; 通过三方库 [TinyPinyin](https://link.jianshu.com?t=https://github.com/promeG/TinyPinyin) 来实现
  **分组**：
  可以通过自定义 RecycleView 的 ItemDecoration 来实现，需要额外处理悬浮窗的显示情况
</code></pre>
</blockquote>
</li>
<li>右侧显示字母快速索引列表，并关联 RecycleView ，可以关联滑动<blockquote>
<p>通过自定义控件来实现</p>
</blockquote>
</li>
</ol>
<h2 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h2><p><strong>说明</strong>：本模块的实现主要参考 <em>小马快跑</em> 的 仿魅族通讯录 项目，并在其基础上进行了适合本项目的优化，在此向原作者致敬。</p>
<blockquote>
<p>Github：<a target="_blank" rel="noopener" href="https://link.jianshu.com/?t=https://github.com/crazyqiang/AndroidStudy/blob/master/app/src/main/java/org/ninetripods/mq/study/recycle/ContactsActivity.java">仿魅族通讯录</a><br>作者： <em>小马快跑</em><br>文章：<a target="_blank" rel="noopener" href="https://www.jianshu.com/p/7b7b7ee80c44">https://www.jianshu.com/p/7b7b7ee80c44</a></p>
</blockquote>
<h3 id="数据库设计"><a href="#数据库设计" class="headerlink" title="数据库设计"></a>数据库设计</h3><table>
<thead>
<tr>
<th>字段名</th>
<th>描述</th>
<th>类型</th>
<th>是否主键</th>
</tr>
</thead>
<tbody><tr>
<td>objectId</td>
<td>唯一标识</td>
<td>String</td>
<td>是</td>
</tr>
<tr>
<td>name</td>
<td>姓名称呼</td>
<td>String</td>
<td>-</td>
</tr>
<tr>
<td>department</td>
<td>部门</td>
<td>String</td>
<td>-</td>
</tr>
<tr>
<td>tel</td>
<td>联系方式</td>
<td>String</td>
<td>-</td>
</tr>
</tbody></table>
<h3 id="安卓实现"><a href="#安卓实现" class="headerlink" title="安卓实现"></a>安卓实现</h3><p>下面介绍下校园通讯录模块实现的主要思路：</p>
<h4 id="step-1-数据排序"><a href="#step-1-数据排序" class="headerlink" title="step 1:  数据排序"></a>step 1:  数据排序</h4><p>依赖 TinyPinyin 库后，对源数据进行加工处理，增加设置 indexTag 字段内容。然后依据该字段进行排序；</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sortData</span><span class="params">(List&lt;Teacher&gt; list)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (list == <span class="keyword">null</span> || list.size() == <span class="number">0</span>) <span class="keyword">return</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; list.size(); i++) &#123;</span><br><span class="line">        Teacher bean = list.get(i);</span><br><span class="line">        String tag = Pinyin.toPinyin(bean.getName().substring(<span class="number">0</span>, <span class="number">1</span>).charAt(<span class="number">0</span>)).substring(<span class="number">0</span>, <span class="number">1</span>);</span><br><span class="line">        <span class="keyword">if</span> (tag.matches(<span class="string">&quot;[A-Z]&quot;</span>)) &#123;</span><br><span class="line">            bean.setIndexTag(tag);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            bean.setIndexTag(<span class="string">&quot;#&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    Collections.sort(list, <span class="keyword">new</span> Comparator&lt;Teacher&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compare</span><span class="params">(Teacher o1, Teacher o2)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="string">&quot;#&quot;</span>.equals(o1.getIndexTag())) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">&quot;#&quot;</span>.equals(o2.getIndexTag())) &#123;</span><br><span class="line">                <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> o1.getIndexTag().compareTo(o2.getIndexTag());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br></pre></td></tr></table></figure>
<h4 id="step-2-数据分组"><a href="#step-2-数据分组" class="headerlink" title="step 2:  数据分组"></a>step 2:  数据分组</h4><p>数据排序完成后，通过自定义 ItemDecoration 来绘制悬浮框及 ItemView 之上的分类Tag</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//用来绘制每个ItemView的边距</span></span><br><span class="line">@Override</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">getItemOffsets</span>(<span class="params">Rect outRect, View view, RecyclerView parent, RecyclerView.State state</span>)</span> &#123;</span><br><span class="line">    <span class="comment">//............省略部分代码............</span></span><br><span class="line">    <span class="built_in">int</span> position = parent.getChildAdapterPosition(view);</span><br><span class="line">    <span class="keyword">if</span> (position == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">//第一条数据有bar</span></span><br><span class="line">        outRect.<span class="keyword">set</span>(<span class="number">0</span>, dividerHeight, <span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (position &gt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (TextUtils.isEmpty(mBeans.<span class="keyword">get</span>(position).getIndexTag())) <span class="keyword">return</span>;</span><br><span class="line">        <span class="comment">//与上一条数据中的tag不同时，该显示bar了</span></span><br><span class="line">        <span class="keyword">if</span> (!mBeans.<span class="keyword">get</span>(position).getIndexTag().<span class="keyword">equals</span>(mBeans.<span class="keyword">get</span>(position - <span class="number">1</span>).getIndexTag())) &#123;</span><br><span class="line">            outRect.<span class="keyword">set</span>(<span class="number">0</span>, dividerHeight, <span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//用来绘制最上面的悬浮框</span></span><br><span class="line">@Override</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onDrawOver</span>(<span class="params">Canvas canvas, RecyclerView parent, RecyclerView.State state</span>)</span> &#123;</span><br><span class="line">     <span class="built_in">int</span> position = ((LinearLayoutManager) (parent.getLayoutManager())).findFirstVisibleItemPosition();</span><br><span class="line">     final <span class="built_in">int</span> bottom = parent.getPaddingTop() + dividerHeight;</span><br><span class="line">     mPaint.setColor(Color.WHITE);</span><br><span class="line">     <span class="comment">//绘制悬浮框的范围</span></span><br><span class="line">     canvas.drawRect(parent.getLeft(), parent.getPaddingTop(), parent.getRight() - parent.getPaddingRight(), parent.getPaddingTop() + dividerHeight, mPaint);</span><br><span class="line">     <span class="comment">//............省略部分代码............</span></span><br><span class="line">     mPaint.setTextSize(<span class="number">40</span>);</span><br><span class="line">     canvas.drawCircle(DpUtil.dp2px(mContext, <span class="number">42.5f</span>), bottom - dividerHeight / <span class="number">2</span>, <span class="number">35</span>, mPaint);</span><br><span class="line">     mPaint.setColor(Color.WHITE);</span><br><span class="line">     canvas.drawText(mBeans.<span class="keyword">get</span>(position).getIndexTag(), DpUtil.dp2px(mContext, <span class="number">42.5f</span>), bottom - dividerHeight / <span class="number">3</span>, mPaint);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//按需绘制ItemView上面的分类Tag</span></span><br><span class="line">@Override</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onDraw</span>(<span class="params">Canvas canvas, RecyclerView parent, RecyclerView.State state</span>)</span> &#123;</span><br><span class="line">    <span class="comment">//............省略部分代码............</span></span><br><span class="line">    final <span class="built_in">int</span> childCount = parent.getChildCount();</span><br><span class="line">    <span class="keyword">for</span> (<span class="built_in">int</span> i = <span class="number">0</span>; i &lt; childCount; i++) &#123;</span><br><span class="line">        final View child = parent.getChildAt(i);</span><br><span class="line">        final RecyclerView.LayoutParams <span class="keyword">params</span> = (RecyclerView.LayoutParams) child.getLayoutParams();</span><br><span class="line">        <span class="built_in">int</span> position = <span class="keyword">params</span>.getViewLayoutPosition();</span><br><span class="line">        <span class="keyword">if</span> (position == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">//第一条数据有bar</span></span><br><span class="line">            drawTitleBar(canvas, parent, child, mBeans.<span class="keyword">get</span>(position), tagsStr.indexOf(mBeans.<span class="keyword">get</span>(position).getIndexTag()));</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (position &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">//与上一条数据中的tag不同时，该显示bar了</span></span><br><span class="line">            <span class="keyword">if</span> (!mBeans.<span class="keyword">get</span>(position).getIndexTag().<span class="keyword">equals</span>(mBeans.<span class="keyword">get</span>(position - <span class="number">1</span>).getIndexTag())) &#123;</span><br><span class="line">                drawTitleBar(canvas, parent, child, mBeans.<span class="keyword">get</span>(position), tagsStr.indexOf(mBeans.<span class="keyword">get</span>(position).getIndexTag()));</span><br><span class="line">            &#125; &#125; </span><br><span class="line">     &#125;  </span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<h4 id="step-3-自定义右侧索引View"><a href="#step-3-自定义右侧索引View" class="headerlink" title="step 3:  自定义右侧索引View"></a>step 3:  自定义右侧索引View</h4><ul>
<li><strong>绘制右侧导航栏字母：</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onDraw</span><span class="params">(Canvas canvas)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//for循环绘制出所有的导航栏字母</span></span><br><span class="line">     <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; indexStr.length(); i++) &#123;</span><br><span class="line">         String textTag = indexStr.substring(i, i + <span class="number">1</span>);</span><br><span class="line">         <span class="keyword">float</span> xPos = (mWidth - mPaint.measureText(textTag)) / <span class="number">2</span>;</span><br><span class="line">         canvas.drawText(textTag, xPos, singleHeight * (i + <span class="number">1</span>) + DpUtil.dp2px(mContext, TOP_MARGIN), mPaint);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>处理滑动事件:</strong></li>
</ul>
<p>在onTouchEvent处理了滑动事件，当手指上下滑动时左侧有个圆跟着滑动，这里用的自定义IndexBar( IndexBar extends ViewGroup，IndexBar包含SideBar )来处理的，当SideBar滑动处于MOVE状态时通过((IndexBar) getParent()).setDrawData()把一系列位置参数传到IndexBar中去</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onTouchEvent</span><span class="params">(MotionEvent event)</span> </span>&#123;</span><br><span class="line">   <span class="comment">//处理按下滑动事件</span></span><br><span class="line">    <span class="keyword">switch</span> (event.getAction()) &#123;</span><br><span class="line">       <span class="keyword">case</span> MotionEvent.ACTION_DOWN:</span><br><span class="line">            <span class="comment">//按下</span></span><br><span class="line">            mPaint.setColor(Color.BLACK);</span><br><span class="line">            invalidate();</span><br><span class="line">       <span class="keyword">case</span> MotionEvent.ACTION_MOVE:</span><br><span class="line">            <span class="comment">//滑动 event.getY()得到在父View中的Y坐标，通过和总高度的比例再乘以字符个数总长度得到按下的位置</span></span><br><span class="line">            <span class="keyword">int</span> position = (<span class="keyword">int</span>) ((event.getY() - getTop() - DpUtil.dp2px(mContext, <span class="number">80</span>)) / mHeight * indexStr.toCharArray().length);</span><br><span class="line">            <span class="keyword">if</span> (position &gt;= <span class="number">0</span> &amp;&amp; position &lt; indexStr.length()) &#123;</span><br><span class="line">                ((IndexBar) getParent()).setDrawData(event.getY(), String.valueOf(indexStr.toCharArray()[position]), position);</span><br><span class="line">                <span class="keyword">if</span> (listener != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    listener.indexChanged(indexStr.substring(position, position + <span class="number">1</span>));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> MotionEvent.ACTION_UP:</span><br><span class="line">            <span class="comment">//抬起</span></span><br><span class="line">            ((IndexBar) getParent()).setTagStatus(<span class="keyword">false</span>);</span><br><span class="line">            mPaint.setColor(Color.GRAY);</span><br><span class="line">            invalidate();</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>主要是在onLayout中把SideBar排列到最右侧，并在onDraw中根据SideBar传过来的一系列位置参数来不断改变圆的位置，</p>
<blockquote>
<p>这里要注意一下，自定义ViewGroup的onDraw()方法默认是不会调用的，如果想执行onDraw方法，可以通过下面两种方法：<br> 1.设置透明背景：<br> 在构造函数中：setBackgroundColor(Color.TRANSPARENT);<br> 或者在xml中：android:background=”@color/transparent”<br> 2.或者可以在构造函数中添加setWillNotDraw(false);</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onLayout</span><span class="params">(<span class="keyword">boolean</span> changed, <span class="keyword">int</span> l, <span class="keyword">int</span> t, <span class="keyword">int</span> r, <span class="keyword">int</span> b)</span> </span>&#123;</span><br><span class="line">     <span class="keyword">int</span> childNum = getChildCount();</span><br><span class="line">     <span class="keyword">if</span> (childNum &lt;= <span class="number">0</span>) <span class="keyword">return</span>;</span><br><span class="line">     <span class="comment">//得到SideBar</span></span><br><span class="line">     View childView = getChildAt(<span class="number">0</span>);</span><br><span class="line">     childWidth = childView.getMeasuredWidth();</span><br><span class="line">     <span class="comment">//把SideBar排列到最右侧</span></span><br><span class="line">     childView.layout((mWidth - childWidth), <span class="number">0</span>, mWidth, mHeight);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onDraw</span><span class="params">(Canvas canvas)</span> </span>&#123;</span><br><span class="line">     <span class="keyword">super</span>.onDraw(canvas);</span><br><span class="line">     <span class="keyword">if</span> (isShowTag) &#123;</span><br><span class="line">         <span class="comment">//根据位置来不断变换Paint的颜色</span></span><br><span class="line">         ColorUtil.setPaintColor(mPaint, position);</span><br><span class="line">         <span class="comment">//绘制圆和文字</span></span><br><span class="line">         canvas.drawCircle((mWidth - childWidth) / <span class="number">2</span>, centerY, circleRadius, mPaint);</span><br><span class="line">         mPaint.setColor(Color.WHITE);</span><br><span class="line">         mPaint.setTextSize(<span class="number">80</span>);</span><br><span class="line">         canvas.drawText(tag, (mWidth - childWidth - mPaint.measureText(tag)) / <span class="number">2</span>, centerY - (mPaint.ascent() + mPaint.descent()) / <span class="number">2</span>, mPaint);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<h4 id="step-4-关联RecycleView"><a href="#step-4-关联RecycleView" class="headerlink" title="step 4: 关联RecycleView"></a>step 4: 关联RecycleView</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">sideBar.setIndexChangeListener(<span class="keyword">new</span> SideBar.indexChangeListener() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">indexChanged</span><span class="params">(String tag)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (TextUtils.isEmpty(tag) || contactList.size() &lt;= <span class="number">0</span>) <span class="keyword">return</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; contactList.size(); i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (tag.equals(contactList.get(i).getIndexTag())) &#123;</span><br><span class="line">                layoutManager.scrollToPositionWithOffset(i, <span class="number">0</span>);</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<hr>
<p>至此，校园通讯录模块基本完成。<br>本文例子中用到多个三方库<a target="_blank" rel="noopener" href="https://link.jianshu.com/?t=https://github.com/amulyakhare/TextDrawable">TextDrawable</a>，<a target="_blank" rel="noopener" href="https://link.jianshu.com/?t=https://github.com/promeG/TinyPinyin">TinyPinyin</a> ，<a target="_blank" rel="noopener" href="https://link.jianshu.com/?t=https://github.com/crazyqiang/AndroidStudy/blob/master/app/src/main/java/org/ninetripods/mq/study/recycle/ContactsActivity.java">仿魅族通讯录</a> 等，再次向各位大佬致敬！</p>
<p>如果本文对你有所帮助，还望可以随手赏一个点赞哈 ~ ~</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Android/" rel="tag"># Android</a>
              <a href="/tags/%E7%A7%91%E5%B8%88%E6%9C%89%E7%BA%A6/" rel="tag"># 科师有约</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/08/25/%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%A6%E4%BD%A0%E6%92%B8%E4%B8%80%E4%B8%AA%E6%A0%A1%E5%9B%ADAPP%EF%BC%88%E4%BA%94%EF%BC%89%EF%BC%9A%E6%96%B0%E9%97%BB%E4%B8%AD%E5%BF%83%E6%A8%A1%E5%9D%97/" rel="prev" title="手把手带你撸一个校园APP（五）：新闻中心模块">
      <i class="fa fa-chevron-left"></i> 手把手带你撸一个校园APP（五）：新闻中心模块
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/08/25/%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%A6%E4%BD%A0%E6%92%B8%E4%B8%80%E4%B8%AA%E6%A0%A1%E5%9B%ADAPP%EF%BC%88%E5%85%AD%EF%BC%89%EF%BC%9A%E5%A4%B1%E7%89%A9%E6%8B%9B%E9%A2%86&%E4%BA%8C%E6%89%8B%E4%BA%A4%E6%98%93%E6%A8%A1%E5%9D%97/" rel="next" title="手把手带你撸一个校园APP（六）：失物招领&二手交易模块">
      手把手带你撸一个校园APP（六）：失物招领&二手交易模块 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%89%8D%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%B3%BB%E5%88%97%E6%96%87%E7%AB%A0"><span class="nav-number">1.0.1.</span> <span class="nav-text">系列文章</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0%E6%95%88%E6%9E%9C"><span class="nav-number">2.</span> <span class="nav-text">实现效果</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%86%E6%9E%90"><span class="nav-number">3.</span> <span class="nav-text">分析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0"><span class="nav-number">4.</span> <span class="nav-text">实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%95%B0%E6%8D%AE%E5%BA%93%E8%AE%BE%E8%AE%A1"><span class="nav-number">4.1.</span> <span class="nav-text">数据库设计</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%89%E5%8D%93%E5%AE%9E%E7%8E%B0"><span class="nav-number">4.2.</span> <span class="nav-text">安卓实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#step-1-%E6%95%B0%E6%8D%AE%E6%8E%92%E5%BA%8F"><span class="nav-number">4.2.1.</span> <span class="nav-text">step 1:  数据排序</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#step-2-%E6%95%B0%E6%8D%AE%E5%88%86%E7%BB%84"><span class="nav-number">4.2.2.</span> <span class="nav-text">step 2:  数据分组</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#step-3-%E8%87%AA%E5%AE%9A%E4%B9%89%E5%8F%B3%E4%BE%A7%E7%B4%A2%E5%BC%95View"><span class="nav-number">4.2.3.</span> <span class="nav-text">step 3:  自定义右侧索引View</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#step-4-%E5%85%B3%E8%81%94RecycleView"><span class="nav-number">4.2.4.</span> <span class="nav-text">step 4: 关联RecycleView</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">vchao</p>
  <div class="site-description" itemprop="description">怀揣好奇，梦想改变世界的菜鸟极客</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">46</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">分类</span>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">冀ICP备 17022751号-1 </a>
      <img src="https://beian.miit.gov.cn" style="display: inline-block;">
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vchao</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
